<template>
  <draw-component
    :drawer-visible="state.show"
    size="720px"
    title="人员管理"
    :show-bottom-btn="false"
    @close-drawer="handleClose()"
  >
    <table-page-content
      ref="tableRef"
      :loading="state.loading"
      :table-data="state.tableList"
      :table-headers="chooseHeaders"
      :table-height="'60vh'"
      :is-pager="false"
      :is-selection="true"
      :is-slot-num="false"
    >
    </table-page-content>
    <template #footBtn>
      <el-button class="btn cancel" @click="handleClose">取消</el-button>
      <el-button class="btn save" type="primary" @click="handleSubmit">保存</el-button>
    </template>
  </draw-component>
</template>

<script lang="ts" setup>
import { chooseHeaders } from '../config'
import { useProxy } from '@/utils/proxy'
import { editUserSubmit, getRoleDetailById } from '../api'
const emit = defineEmits(['handleAdded'])
const tableRef = ref()
const { proxy } = useProxy()
const state = reactive({
  loading: false,
  currRoleId: '',
  show: false,
  tableList: []
})
// 关闭回调
const handleClose = () => {
  state.currRoleId = ''
  state.show = false
}
// 获取列表数据
const getList = (list: any[]) => {
  state.loading = true
  state.tableList = []
  proxy.$api
    .getUserList<any>()
    .then((res) => {
      state.tableList = res.data
      if (list?.length > 0) {
        nextTick(() => {
          state.tableList.forEach((item: any) => {
            if (list.some((v) => v.id == item.id)) {
              tableRef.value.toggleRowSelection(item, true)
            }
          })
        })
      }

      state.loading = false
    })
    .catch(() => {
      state.loading = false
    })
}
// 获取详情
const getRoleDetail = async () => {
  let { data } = await getRoleDetailById<any>(state.currRoleId)
  getList(data.roleUserResponseDtoList)
}
// 提交
const handleSubmit = async () => {
  let selectItem = tableRef.value.getAllSelectItem()
  let userIdList = selectItem.map((v: any) => v.userId)
  await editUserSubmit(state.currRoleId, { userIdList })
  proxy.$message.msgSuccess('保存成功')
  emit('handleAdded')
  handleClose()
}
defineExpose({ state, getRoleDetail })
</script>

<style lang="scss" scoped></style>
